package com.wsoft.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wsoft.constant.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.annotation.InitRedisCache;
import com.wsoft.core.exception.Asserts;
import com.wsoft.system.dto.SysLevelDTO;
import com.wsoft.system.entity.SysLevelEntity;
import com.wsoft.system.mapper.SysLevelMapper;
import com.wsoft.system.query.level.SysLevelReq;
import com.wsoft.system.service.ISysLevelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 职务级别 服务实现类
 * </p>
 *
 * @author juiet
 * @since 2024年09月11日 15:07:09
 */
@Service
public class SysLevelServiceImpl extends ServiceImpl<SysLevelMapper, SysLevelEntity> implements ISysLevelService {

    @Override
    public boolean insert(SysLevelDTO dto) {
        SysLevelEntity entity = Convert.convert(SysLevelEntity.class, dto);
        QueryWrapper<SysLevelEntity> query = new QueryWrapper<>();
        query.lambda().eq(SysLevelEntity::getCode, entity.getCode());
        if (count(query) > 0) {
            Asserts.fail("[sys.code.exist]");
        }
        return save(entity);
    }

    @Override
    @InitRedisCache(type = RedisKeyConstant.LEVEL_CACHE,
                    value = "id")
    public boolean update(SysLevelDTO dto) {
        SysLevelEntity entity = Convert.convert(SysLevelEntity.class, dto);
        QueryWrapper<SysLevelEntity> query = new QueryWrapper<>();
        query.lambda().eq(SysLevelEntity::getCode, entity.getCode())
                .ne(SysLevelEntity::getId, entity.getId());
        if (count(query) > 0) {
            Asserts.fail("[sys.code.exist]");
        }
        return updateById(entity);
    }

    @Override
    @GetRedisCache(type = RedisKeyConstant.LEVEL_CACHE,
                            value = "id")
    public SysLevelEntity getLevelById(Long id) {
         return getById(id);
    }

    @Override
    @InitRedisCache(type = RedisKeyConstant.LEVEL_CACHE,
            value = "id")
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    public PageInfo<SysLevelEntity> pageLevel(SysLevelReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        QueryWrapper<SysLevelEntity> query = new QueryWrapper<>();
        //编码
        if (StrUtil.isNotBlank(req.getCode())) {
            query.lambda().like(SysLevelEntity::getCode, req.getCode());
        }
        //名称
        if (StrUtil.isNotBlank(req.getName())) {
            query.lambda().eq(SysLevelEntity::getName, req.getName());
        }
        query.lambda().orderByAsc(SysLevelEntity::getSort);
        return PageInfo.of(list(query));
    }
}
